package com.example.redisstudy.concurrent;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;



//https://cloud.tencent.com/developer/article/2398608 来源:深入理解Java中的线程安全List：CopyOnWriteArrayList原理和应用

// 新闻类
class News {
    private String title;
    private String content;

    public News(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public String getTitle() {
        return title;
    }

    public String getContent() {
        return content;
    }

    @Override
    public String toString() {
        return "News{" +
                "title='" + title + '\'' +
                ", content='" + content + '\'' +
                '}';
    }
}

// 新闻发布系统类
public class NewsPublisherSystem {
    // 使用CopyOnWriteArrayList存储新闻列表
    private final List<News> newsList = new CopyOnWriteArrayList<>();

    // 添加新闻
    public void addNews(News news) {
        newsList.add(news);
        System.out.println("新闻已添加: " + news);
    }

    // 获取新闻列表
    public List<News> getNewsList() {
        return newsList;
    }

    // 模拟多线程添加和读取新闻
    public void simulate() {
        ExecutorService executor = Executors.newFixedThreadPool(10);

        // 提交5个添加新闻的任务
        for (int i = 0; i < 5; i++) {
            final int index = i;
            executor.submit(() -> {
                for (int j = 0; j < 10; j++) {
                    News news = new News("新闻标题" + index + "-" + j, "新闻内容" + index + "-" + j);
                    addNews(news);
                    try {
                        // 模拟新闻发布的延迟
                        TimeUnit.MILLISECONDS.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        // 提交5个读取新闻列表的任务
        for (int i = 0; i < 5; i++) {
            executor.submit(() -> {
                for (int j = 0; j < 20; j++) {
                    System.out.println("当前新闻列表: " + getNewsList());
                    try {
                        // 模拟读取新闻列表的延迟
                        TimeUnit.MILLISECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        // 关闭执行器服务
        executor.shutdown();
        try {
            if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) {
        NewsPublisherSystem system = new NewsPublisherSystem();
        system.simulate();
    }
}